package com.wbl.featurn.login

import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import com.wbl.common.UiEffect

@Composable
fun LoginPage(
    viewModel: LoginViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    val context = LocalContext.current
    LaunchedEffect(Unit) {
        viewModel.effect.collect { effect ->
            when (effect) {
                is UiEffect.ShowToast -> {
                    Toast.makeText(context, effect.message, Toast.LENGTH_SHORT).show()
                }

                else -> {

                }
            }
        }
    }

    Box(
        modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            OutlinedTextField(value = state.username, onValueChange = { it ->
                viewModel.handleIntent(LoginIntent.UpdateUserName(it))
            }, label = {
                Text(text = "UserName")
            }, placeholder = {
                Text(text = "UserName")
            })
            OutlinedTextField(value = state.password, onValueChange = {
                viewModel.handleIntent(LoginIntent.UpdatePassword(it))
            }, label = {
                Text(text = "Password")
            }, placeholder = {
                Text(text = "Password")
            })
            Button(onClick = {
                viewModel.login()
            }, content = {
                Text(text = "Login")
            })
        }
    }
}